package com.xkh.hadoop.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;

/**
 * @author xkh
 * @since 2021/6/29 0029
 */
@Slf4j
@Component
public class RedisLock {

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    public boolean tryLock(String key, String value, int expireTime) {
        long start = System.currentTimeMillis();
        long end = expireTime / 2;
        Boolean flag = false;
        //毫秒
        while (true) {
            //否则循环等待，在timeout时间内仍未获取到锁，则获取失败
            if (System.currentTimeMillis() - start > end) {
                log.error("申请锁(" + key + "," + value + ")失败");
                return false;
            }
            flag = redisTemplate.opsForValue().setIfAbsent(key, value, expireTime, TimeUnit.MILLISECONDS);
            if (flag) {
                log.info("申请锁(" + key + "," + value + ")成功");
                return true;
            }
        }
    }


    public void unLock(String key, String value) {
        String script = "if redis.call('get', KEYS[1]) == KEYS[2] then return redis.call('del', KEYS[1]) else return 0 end";
        RedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
        Long result = redisTemplate.execute(redisScript, Arrays.asList(key, value));
        if (result == null || result == 0) {
            log.error("释放锁(" + key + "," + value + ")失败,该锁不存在或锁已经过期");
        } else {
            log.info("释放锁(" + key + "," + value + ")成功");
        }
    }

}
